import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
	NProgress.start()
	const hasToken = getToken()
	const addRoutes = store.state.permission.addRoutes
	if (hasToken) {
		if (to.path === '/login' || to.path === '/404') {
			next({ path: '/' })
			NProgress.done()
		} else {
			if (addRoutes.length === 0) {
				store.dispatch('user/getMerchantInfo')
				store.dispatch('user/getMerchantList')
				// 获取货币符号
				store.dispatch('user/getCurrencySymbol')
				store.dispatch('user/getCurrencySymbol')
				store.dispatch('user/updateCurrentAccountPeriod')
				try {
					// await store.dispatch('user/getDictList')

					// const accessRoutes = await store.dispatch(
					// 	'permission/generateRoutes',
					// 	[]
					// )
					// router.addRoutes(accessRoutes)

					await store.dispatch('user/getDictList')
					const roles = await store.dispatch('user/getRoles')
					if (roles) {
						const accessRoutes = await store.dispatch(
							'permission/generateRoutes',
							roles
						)
						router.addRoutes(accessRoutes)
					}
					next({ ...to, replace: true })
				} catch (e) {
					await store.dispatch('user/clearAllCaches')
					next(`/login?redirect=${to.path}`)
					NProgress.done()
				}
			} else {
				try {
					// await store.dispatch('user/getInfo')
					next()
				} catch (error) {
					await store.dispatch('user/clearAllCaches')
					Message.error(error || 'Has Error')
					next(`/login?redirect=${to.path}`)
					NProgress.done()
				}
				next()
			}
		}
	} else {
		if (whiteList.indexOf(to.path) !== -1) {
			next()
		} else {
			next(`/login?redirect=${to.path}`)
			NProgress.done()
		}
	}
})
router.afterEach(() => {
	NProgress.done()
})
